<?php

namespace app\admin\model\batchpay;

use app\admin\model\Joinpay;
use app\common\library\Log;
use fast\Http;
use think\Db;
use think\Model;
use think\Log as recordLog;


class Lists extends Model
{

    

    

    // 表名
    protected $name = 'batchpay_lists';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text'
    ];
    

    
    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2'), '-1' => __('Status -1'), '-2' => __('Status -2')];
    }

    public function ispublic()
    {
        return ['0' => __('Ispublic 0'), '1' => __('Ispublic 1')];
    }



    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    // 在对应的模型类中（如application/common/model/YourModel.php）
    public function getFieldComments()
    {
        $table = $this->getTable(); // 获取当前模型对应的表名
        $database = config('database.fa_batchpay_lists'); // 获取数据库名
        $sql = "SELECT COLUMN_NAME, COLUMN_COMMENT FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?";
        $comments = Db::query($sql, [$database, $table]);
        $result = [];
        foreach ($comments as $item) {
            $result[$item['COLUMN_NAME']] = $item['COLUMN_COMMENT'];
        }
        return $result;
    }

    public function callback($url,$status,$order) {

        $platform = Db('platformLists')->where(['enname' => $order['platform']])->find();

        // 最大请求次数
        $maxRequests = 3;

        // 当前请求次数
        $currentRequests = 1;

        //回传银行信息
        $data = [
            'price' => sprintf("%.2f", $order['money']),
            'realmoney' => sprintf("%.2f", $order['realmoney']),
            'fee' => $order['fee'],
            'callbackurl' => $url,
            'status' => (string)$status,
            'ordersn' => $order['ordersn'],
            'type' => 'batchpay'
        ];

        $datas = $data;

        $datas['sign'] = (new Joinpay)->hmacRequest($datas,$platform['key']);

        $requestUrl = $url . '?' . http_build_query($datas);
        recordLog::record($requestUrl);
        // 立即请求一次
        $response = Http::get($requestUrl);

        // 检查响应
        if ($response == 'success') {
            $data['notify_status'] = 1;
            $data['time'] = date('Y-m-d H:i:s');

            Db('batchpayNotify')->insert($data);

            Db('batchpayLists')->where(array('id' => $order['id']))->update(['notify_status' => 1]);
            return true;
        }

        // 如果第一次请求失败，继续请求
        while ($currentRequests < $maxRequests) {
            // 等待10秒
//            sleep(10);

            // 发起请求
            $response = Http::get($requestUrl);

            // 检查响应
            if ($response == 'success') {
                $data['batchpayNotify'] = 1;
                Db('batchpayNotify')->insert($data);
                return true;
            }else{
                // 如果所有请求都失败，记录失败状态
                $data['notify_status'] = 2;
                Db('batchpayNotify')->insert($data);
                Db('batchpayLists')->where(array('id' => $order['id']))->update(['notify_status' => 2]);

            }

            // 增加请求次数
            $currentRequests++;
        }


        return false;
    }





}
